package com.ithuangyl.common.net.callback;

import android.os.Handler;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.ithuangyl.common.config.ConfigKeys;
import com.ithuangyl.common.config.Latte;
import com.ithuangyl.common.loader.LatteLoader;
import com.ithuangyl.common.loader.LoaderStyle;
import com.ithuangyl.common.net.RestResCode;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * author : itHuang
 * e-mail : ithuangyl@163.com
 * date   : 2020/7/15 22:50
 */
public class RequestCallbacks<T> implements Callback<String> {

    private final String TAG = "RequestCallbacks";
    private final IRequest REQUEST;
    private final Class<T> CLAZZ;
    private final ISuccess SUCCESS;
    private final IFailure FAILURE;
    private final IError ERROR;
    private final LoaderStyle LOADER_STYLE;
    private static final Handler HANDLER = Latte.getConfiguration(ConfigKeys.HANDLER);

    public RequestCallbacks(Class<T> clazz, IRequest request, ISuccess success, IFailure failure, IError error, LoaderStyle style) {
        if (clazz == null) {
            Log.e(TAG, "RestClient property clazz is null!");
        }
        this.CLAZZ = clazz;
        this.REQUEST = request;
        this.SUCCESS = success;
        this.FAILURE = failure;
        this.ERROR = error;
        this.LOADER_STYLE = style;
    }

    @Override
    public void onResponse(Call<String> call, Response<String> response) {
        if (response.isSuccessful()) {
            if (call.isExecuted()) {
                if (SUCCESS != null) {
                    String result = response.body();
                    SUCCESS.onSuccess(JSON.parseObject(result, CLAZZ));
                }
            } else {
                Log.e(TAG, "Retrofit onResponse() ---------->" + response.message());
            }
        } else {
            Log.e(TAG, "Retrofit onResponse() ---------->" + response.message());
            if (ERROR != null) {
                ERROR.onError(response.code(), response.message());
                return;
            } else if (FAILURE != null) {
                FAILURE.onFailure(response.code(), response.message());
            }
        }
        onRequestFinish();
    }

    @Override
    public void onFailure(Call<String> call, Throwable t) {
        Log.e(TAG, "Retrofit onFailure() ---------->" + t.getMessage());
        if (FAILURE != null) {
            FAILURE.onFailure(RestResCode.ERROR_FAILURE, t.getMessage());
        }
        if (REQUEST != null) {
            REQUEST.onRequestEnd();
        }
        onRequestFinish();
    }

    private void onRequestFinish() {
        final Integer delayed = Latte.getConfiguration(ConfigKeys.LOADER_DELAYED);
        if (LOADER_STYLE != null) {
            HANDLER.postDelayed(new Runnable() {
                @Override
                public void run() {
                    LatteLoader.stopLoading();
                }
            }, delayed);
        }
    }
}
